package com.zzxx.exam.entity;

import com.zzxx.exam.util.Config;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实体数据管理, 用来读取数据文件放到内存集合当中
 */
public class EntityContext {
    private Config config;

    public Config getConfig() {
        return config;
    }

    //存放用户
    private Map<Integer,User> users = new HashMap<>();
    //存放问题集合 一个难度级别下面对应这个难度的所有题目
    private Map<Integer, List<Question>> questions = new HashMap<>();
    //存放考试规则
    StringBuilder rules = new StringBuilder();

    public Map<Integer, User> getUsers() {
        return users;
    }

    public Map<Integer, List<Question>> getQuestions() {
        return questions;
    }

    public EntityContext(Config config) {
        this.config = config;
        String UserFile = config.getString("UserFile");
        String QuestionFile = config.getString("QuestionFile");
        String RulesFile = config.getString("ExamRule");
        loadUsers(UserFile);
        loadQuestions(QuestionFile);
        //users.put(1001,new User("lucy",1001,"1234"));
    }


    //将user.txt读出来存入到Map<Integer,User>中
    void loadUsers(String userFile){
        BufferedReader bf = null;
        String line = null;
        try {
            bf = new BufferedReader(new InputStreamReader(new FileInputStream(userFile)));
            while ((line=bf.readLine())!=null){
                if(line.startsWith("#")||line.equals("")){
                   continue;
                }
                User user = parseUser(line);
                users.put(user.getId(),user);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bf!=null){
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(users.size());
        }
    }

    //将题目读入questions集合 Map<Integer,List<Question>> questions
    void loadQuestions(String questionFile){
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new InputStreamReader(new FileInputStream(questionFile)));
            String line = null;
            while((line=bf.readLine()) != null){
                Question question = parseQuestion(line, bf);
                addQuestion(question);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bf!=null){
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public StringBuilder getConfigRules(){
        StringBuilder sb = new StringBuilder();
        sb.append(config.getString("ExamRule"));
        return sb;
    }
    public StringBuilder LoadRules(StringBuilder RulesFile){
        BufferedReader bf = null;
        StringBuilder sb = new StringBuilder();
        try {
            bf = new BufferedReader(new InputStreamReader(new FileInputStream(RulesFile.toString())));
            String line = null;
            while((line=bf.readLine()) != null){
                sb.append(line);
                sb.append("\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bf!=null){
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }

    /**
     * 将question对象添加到questions集合当中去
     * @param question
     */
    private void addQuestion(Question question) {
        List<Question> list = this.questions.get(question.getLevel());
        if(list==null){
            list = new ArrayList<>();
            questions.put(question.getLevel(),list);
        }
        list.add(question);
    }

    public User getUserById(int id) {
        return users.get(id);
    }
    public User parseUser(String str){
        String[] strings = str.split(":");
        User user = new User();
        user.setId(Integer.parseInt(strings[0]));
        user.setName(strings[1]);
        user.setPassword(strings[2]);
        user.setPhone(strings[3]);
        user.setEmail(strings[4]);
        return user;
    }

    /**
     *解析Question对象
     * @param str @answer=2/3,score=5,level=5   @answer=  ,score=    ,level=
     * @param br
     */
    private Question parseQuestion(String str, BufferedReader br) {
        Question question = new Question();
        try {
            String[] data = str.split("[@,][a-z]+=");
            // {"", "2/3", "5", "5"}
            question.setAnswers(parseAnswer(data[1]));
            question.setScore(Integer.parseInt(data[2]));
            question.setLevel(Integer.parseInt(data[3]));
            question.setTitle(br.readLine());
            List<String> option = new ArrayList<>();
            option.add(br.readLine());
            option.add(br.readLine());
            option.add(br.readLine());
            option.add(br.readLine());
            question.setOptions(option);
            question.setType(question.getAnswers().size()==1? Question.SINGLE_SELECTION:Question.MULTI_SELECTION);//0表示单选,1表示多选
        } catch (IOException e) {
            e.printStackTrace();
        }
        return question;
    }

    /**
     * 解析 2/3正确答案
     * @param datum
     * @return
     */
    private List<Integer> parseAnswer(String datum) {
        List<Integer> answers = new ArrayList<>();
        String[] data = datum.split("/");
        for (String str:data) {
            answers.add(Integer.valueOf(str));
        }
        return answers;
    }
    public int getLimit(){
        return config.getInt("TimeLimit");
    }
    public String getTitle(){
        return config.getString("PaperTitle");
    }

    /**
     * 返回不同等级的问题集合
     * @param level
     * @return
     */
    public List<Question> getQuestionsByLevel(int level){
        return questions.get(level);
    }
}
